#!/bin/bash

LANG=C # good for the printf version - see stackoverflow.com/a/8402305
precision=3 # digits after the '.'
grabber="grabc"

function usage {
	echo "$1

	convert one 6 digit hex color
	to 3 rgb values between 0 and 1.

	argument: either one 6 digit hex color
	\"#nnnnnn\" (you must use quotes)
	or -g to grab with $grabber
"
exit 1
}

[[ $# != 1 ]] && usage "wrong number of arguments."

if [[ "$1" == "-g" ]]; then
	if which $grabber >/dev/null 2>&1; then
		color="$($grabber 2>/dev/null)"
	else
		usage "$grabber not found in \$PATH."
	fi
else
	[[ ! "$1" =~ ^#[0-9A-Fa-f]{6}$ ]] && usage "wrong format: $1"
	color="$1"
fi

red="$((16#${color:1:2}))"
grn="$((16#${color:3:2}))"
blu="$((16#${color:5:2}))"

#~ for color in "$red" "$grn" "$blu"
#~ do
	#~ bc<<<"scale=$precision;x=${color}/255;if(x>0 && x<1) print 0;print x"
	#~ ##~ bc<<<"ibase=16;obase=10;scale=$precision;${color}/FF"
#~ done

#~ bc<<<"scale=$precision;x=($red/255)*1.0;if(x>0 && x<1) print 0;print x"
#~ printf ' '
#~ bc<<<"scale=$precision;x=($grn/255)*1.0;if(x>0 && x<1) print 0;print x"
#~ printf ' '
#~ bc<<<"scale=$precision;x=($blu/255)*1.0;if(x>0 && x<1) print 0;print x"
#~ printf '\n'

# printf version
printf "%${precision}.${precision}f " $(bc<<<"scale=$precision;$red/255")
printf "%${precision}.${precision}f " $(bc<<<"scale=$precision;$grn/255")
printf "%${precision}.${precision}f\n" $(bc<<<"scale=$precision;$blu/255")
